public with sharing class ScheduledCargoGetNCDataController {
	public String sid ;//联查Id
	public Boolean isErr {get;set;}//
	public String  msg {get;set;} 
	public String resJson {get;set;}
	public Boolean isAccount ;
	public Account acc ;
	public ScheduledCargo__c sc ;

    public ScheduledCargoGetNCDataController() {
        
        sid = System.currentPageReference().getParameters().get('id');
      	sc = new ScheduledCargo__c();
      	acc = new Account();
    }

    public void init(){
    	setNil();
    	if(sid == null){
    		setErr('页面打开错误!');
    		return;
    	}
    	try{
    		SobjectType sot =Id.valueOf(sid).getSobjectType();
    		isAccount =  sot == Account.SObjectType;
    		sid = String.valueOf(Id.valueOf(sid));

    		
			
			if(isAccount){
				acc = [select Id ,AccountNumber from Account where id=:sid];
			}else{
				 sc = [select Id ,IsSycToNc__c,Customer__r.AccountNumber from ScheduledCargo__c where Id =:sid ];
				if(sc.IsSycToNc__c == false){
					setErr('未同步单据不能联查!');
				}
			}
    		

    	}catch(Exception e){
    		setErr('页面打开错误!'+e.getMessage());
    	}
    }
    private void setErr(String message ){
    	isErr= true;
    	msg = message;
    }
    private Map<String,SameBatchNumber__c> getDetails(){
    	Map<String,SameBatchNumber__c> tmp = new Map<String,SameBatchNumber__c>();
    	
    	String sql = 'select Id,Inventory__r.ProductName__c,Inventory__r.Brand__c,Inventory__r.NCCode__c,BatchNumber__c,Inventory__r.Name,'
    	+'Name ,CargoDetail__r.Customer__r.Name,Inventory__r.Unit__c,Inventory__r.Model__c,Inventory__r.SerialNo__c,Inventory__r.Spec__c, '
    	+'SendMount1__c,SendMount2__c,SendMount3__c,SendMount4__c,SendMount5__c,SendMount6__c,SendMount7__c,SendMount8__c,'
    	+'SendMount9__c,SendMount10__c,SendMount11__c,SendMount12__c,SendYear__c ,CargoDetail__r.Customer__c,ExpirationDate__c,CargoDetail__r.Name  '
    	+'from SameBatchNumber__c';
    	if(isAccount){
    		sql += ' where CargoDetail__r.Customer__c =\''+sid+'\''; 
    	}else{
    	 sql += ' where CargoDetail__c =\''+sid+'\''; 
    	}

    	for (SameBatchNumber__c sbn  :Database.query(sql) ) {
    		tmp.put(sbn.Id ,sbn);
    	}

    	return tmp;
    }
    public void getNCData(){

     	String url = Label.queryResposityURL;
     	String whereStr = '';
     	 //if(isAccount )whereStr += ' and cu.custcode = \''+ acc.AccountNumber +'\' ';
     	 //if(isScargo) whereStr += ' and sb.vdef4 = \''+String.valueOf(Id.valueOf(sid))+'\'';
     	 //if(!isScargo && !isAccount) return;
    	HttpRequest req = new HttpRequest();
     	String sql = '{"data":" '+ getSql()+whereStr+'"}';
     	System.debug(sql);
      	req.setBody(sql);
      	req.setMethod('POST');
      	req.setHeader('Content-Type','text/plain');
      	req.setEndpoint(url);
      	HttpResponse res = Utils.postRequest(req, 2);
      ///返回结果处理
        if (res.getStatusCode() == 200) {
        	System.debug(res.getBody());
            Map<String,Object> r = null;
              //如果是测试
                if(Test.isRunningTest()){
                  Map<String,Object>  resBody= new Map<String,Object>();
                  resBody.put('code','0');
                  resBody.put('result','{\"result_msg\":\"查询成功！\",\"result\":1,\"data\":[{\"pk_corp\":\"1005\",\"vreceiptcode\":\"SO1811020001\",\"measname\":\"盒\",\"user_name\":\"四川大学华西医院\",\"ck_dvdate\":\"2019-08-25\",\"vdef4\":\"a160k000000lWF9AAM\",\"invcode\":\"110100100001\",\"fz_dvdate\":\"2019-08-25\",\"vdef3\":\"a150k000001B8l0AAC\",\"invname\":\"总蛋白测定试剂盒（双缩脲法）\",\"invpinpai\":\"迈克生物\",\"custname\":\"四川大学华西医院\",\"tatoldefnum\":10,\"psnname\":\"祝晓琳\",\"ck_vlot\":\"dxx1806252\",\"ck_num\":8,\"lastfreezenum\":0,\"invmnecode\":\"CH0101001\",\"vdef5\":\"SFBH\",\"totalfreezenum\":10,\"invtype\":\"TP:7170单\",\"fz_vlot\":\"dxx1806252\",\"invspec\":\"1\"}]}');
                    r =  resBody;
                }else{
                  r= (Map<String,Object> ) JSON.deserializeUntyped(res.getBody());
                }
        	// r = (Map<String,Object>) JSON.deserializeUntyped(res.getBody());
        	if(r.get('code') == 0 || r.get('code') == '0'){
        		Map<String, List<NCDataBean>>ncdMap  = new Map<String,List<NCDataBean>>();
        		 Map<String,Object> rs = (Map<String,Object>) JSON.deserializeUntyped(((String)r.get('result')));
	            if( rs.get('result') == 1 ){
	            	Map<String,SameBatchNumber__c> sbMap =  getDetails();
	                List<Object> datas = (List<Object>)rs.get('data');
	               for(Object ob :datas){


	               		Map<String,Object> ncd   = (Map<String,Object>)ob;
	               		if(ncd.get('vdef3') != null){
	                		NCDataBean rd = new NCDataBean(ncd,sbMap.get(String.valueOf(ncd.get('vdef3'))));
	                		List<NCDataBean> nctmp = ncdMap.get(String.valueOf(ncd.get('vdef3')));
	                		if(nctmp == null ) nctmp = new List<NCDataBean> ();
	                		nctmp.add(rd);
	                		ncdMap.put(String.valueOf(ncd.get('vdef3')),nctmp);
	               		}

               
	                }
	                List<NCDataBean> aLi = new  List<NCDataBean> ();
	                for (String  k: ncdMap.keyset() ) {
	                	aLi.addAll(ncdMap.get(k));
	                }


	                for (String k : sbMap.keyset() ) {
	                	System.debug('===>'+k);
	                	System.debug('===>'+ncdMap.containsKey(k));
	                	if(!ncdMap.containsKey(k)){
	                		aLi.add(new NCDataBean(null,sbMap.get(k) ));
	                	}
	                }

	               /* for (Integer i = 0; i < 5;i ++ ) {
	                	ebList.add(new NCDataBean(String.valueOf(12)));
	                }*/
	               System.debug(aLi.size());
      				resJson = EncodingUtil.urlEncode(JSON.serialize(aLi), 'UTF-8') ;

	           	}else{
	           		msg = String.valueOf(rs.get('result_msg'));
	           	}

      		//resJson = EncodingUtil.urlEncode(res.getBody(), 'UTF-8') ;
		    }else{
		    	msg = '查询备货数据失败 : '+String.valueOf(r.get('msg'));
		    	 ///System.debug(res.toString());
		    	//resJson = EncodingUtil.urlEncode('{"result":"","code":"1","msg":"接口错误,查询失败!"}','UTF-8');
		    }

	    }else{
	    	msg = '查询备货数据失败 : '+res.getBody();
	    }
    }


    private String getSql(){
    	/*String sql = ' select sp.pk_corp,cp.unitcode,sp.vreceiptcode, cu.custcode, cu.custname,usr.user_name, '
		+' str.storname,psn.psnname,iv.invcode,iv.invmnecode, '
		+' iv.invname,iv.invspec,iv.invtype,iv.invpinpai,ms.measname,a2.dconsigndate, '
		+' a4.vreceiptcode saleorder,a2.nnumber, '
		+' ib.noutnum, ib.dbizdate,ib.vbatchcode, '
		+' im.def15 gwls,sb.vdef3,sb.vdef4,sb.vdef5 '
		+' from so_preorder_b  sb  '
		+' left join so_preorder  sp on sb.pk_preorder=sp.pk_preorder '
		+' left join  so_saleorder_b a2  on sb.pk_preorder_b=a2.csourcebillbodyid  ' 
		+' left join  so_sale  a4 on a4.csaleid=a2.csaleid '
		+' left join ic_general_b  ib on ib.csourcebillbid=a2.corder_bid '
		+' left join ic_general_h ih on ih.cgeneralhid=ib.cgeneralhid  '
		+' left join bd_busitype a5 on a5.pk_busitype=a4.cbiztype '
		+' left join  bd_invbasdoc iv on iv.pk_invbasdoc=sb.cinvbasdocid '
		+' join bd_invmandoc im on im.pk_invbasdoc=iv.pk_invbasdoc and im.pk_corp=sb.pk_corp '
		+ ' left  join moq_sy_syyp  sy on sy.vmedcode=iv.invcode  and sy.pk_corp=sb.pk_corp '
		+ ' join bd_measdoc ms on ms.pk_measdoc=iv.pk_measdoc '
		+ ' join bd_cumandoc cum on cum.pk_cumandoc=sp.ccustomerid '
		+ ' join bd_cubasdoc cu on cum.pk_cubasdoc=cu.pk_cubasdoc '
		+ ' join sm_user  usr on usr.cuserid=sp.coperatorid '
		+' left  join bd_stordoc str on str.pk_stordoc=ih.cwarehouseid '
		+ ' join bd_psndoc  psn on psn.pk_psndoc=sp.cemployeeid '
		+ ' left join bd_corp cp on cp.pk_corp=sp.pk_corp  '
		+' where sb.dr=0 and sp.dr=0  '

		+' and sb.vdef5=\'SFBH\' ';*/

		String sql = 'select sp.pk_corp,sp.vreceiptcode,  cu.custname,usr.user_name,';
		sql+='psn.psnname,iv.invcode,iv.invmnecode,';
		sql+='iv.invname,iv.invspec,iv.invtype,iv.invpinpai,ms.measname, ';
		sql+='a4.vreceiptcode, ';
		sql+='hb.fz_vlot, hb.fz_dvdate,hb.totalfreezenum, hb.tatoldefnum ,hb.lastfreezenum, ';
		sql+='hb.ck_vlot ,hb.ck_dvdate, hb.ck_num, ';
		sql+='sb.vdef3,sb.vdef4,sb.vdef5 ';
		sql+='from so_preorder_b  sb  ';
		sql+='left join so_preorder  sp on sb.pk_preorder=sp.pk_preorder ';
		sql+='left join  so_saleorder_b a2  on sb.pk_preorder_b=a2.csourcebillbodyid   ';
		sql+='left join  so_sale  a4 on a4.csaleid=a2.csaleid ';
		sql+='left join ';
		sql+='(select nvl(a1.CCORRESPONDBID,ib.csourcebillbid) as csourcebillbid, ';
		sql+='nvl(a1.cinvbasid,ib.cinvbasid) as cinvbasid, ib.vbatchcode as ck_vlot,ib.dvalidate as ck_dvdate,ib.noutnum as ck_num,  ';
		sql+='a1.vbatchcode as fz_vlot,a1.dvalidate as fz_dvdate,a1.totalfreezenum ,a1.tatoldefnum,a1.lastfreezenum ';
		 sql+='from   ';
		 sql+='(select igb.csourcebillbid, ';
		 sql+='igb.cinvbasid,igb.vbatchcode,bt.dvalidate,sum(igb.noutnum) as noutnum ';
		sql+='from ic_general_b igb left join scm_batchcode bt on bt.pk_invbasdoc=igb.cinvbasid and bt.vbatchcode=igb.vbatchcode ';
		 sql+='where igb.dr=0 and igb.cbodybilltypecode=\'4C\'  ';
		 if(!isAccount){
		 	
			 sql+='and igb.csourcebillbid in (select s2.corder_bid from so_saleorder_b s2 where s2.csourcebillbodyid in ( select distinct s1.pk_preorder_b from so_preorder_b  s1 ';
			sql+='where s1.vdef4=\''+sid+'\'   ))';
		}
		 sql+=' group by  igb.csourcebillbid, ';
		 sql+=' igb.cinvbasid,igb.vbatchcode,bt.dvalidate )   ib  ';
		sql+=' full outer  join  ';
		sql+='( ';
		sql+='select fz1.CCORRESPONDBID,fz1.cinvbasid,fz1.vbatchcode,fz1.dvalidate, ';
		sql+='sum(case when fz1.dthawdate is  null then  fz1.nfreezenum else fz1.ndefrznum end ) as totalfreezenum, ';
		sql+='sum(fz1.ndefrznum) as tatoldefnum,  ';
		sql+='sum(case when fz1.dthawdate is  null then  fz1.nfreezenum else 0 end ) as lastfreezenum ';
		sql+='from  ic_freeze  fz1 where fz1.dr=0   ';
		sql+='group by fz1.CCORRESPONDBID,fz1.cinvbasid,fz1.vbatchcode,fz1.dvalidate   ';
		 sql+=')   a1  on a1.ccorrespondbid= ib.csourcebillbid  and a1.vbatchcode=ib.vbatchcode  ';
		 sql+=')   hb  on hb.csourcebillbid=a2.corder_bid 	 '	  ;
		sql+='left join  bd_invbasdoc iv on iv.pk_invbasdoc=sb.cinvbasdocid ';
		 sql+='join bd_measdoc ms on ms.pk_measdoc=iv.pk_measdoc ';
		 sql+='join bd_cumandoc cum on cum.pk_cumandoc=sp.ccustomerid ';
		 sql+='join bd_cubasdoc cu on cum.pk_cubasdoc=cu.pk_cubasdoc ';
		 sql+='join sm_user  usr on usr.cuserid=sp.coperatorid ';
		 sql+='join bd_psndoc  psn on psn.pk_psndoc=sp.cemployeeid ';
		sql+='where sb.dr=0 and nvl(a2.dr,0)=0 and nvl(a4.dr,0)=0 and sp.dr=0 and sb.vdef5=\'SFBH\' ';
		
		if(!isAccount){
			sql+=' and sb.vdef4 = \''+sid+'\' ';
		}else{
			sql += 'and cu.custcode = \'' +acc.AccountNumber + '\' ';
		}
		//+' and cu.custcode = \'614854\' ';

    	return sql;
    }
    public void setNil(){
    	resJson = '';
    	msg = '';
    }
    public class NCDataBean{

    	public string name ;//SF单据号
    	public String  h_name ;//SF主表单号
    	//public String vreceiptcode;//预订单号
    	public String custname ;//客户名称
    	public String invcode ;//存货代码
    	//public String storname ; //仓库
    	public String invmnecode ; //货号
    	public String invname; //产品名称
    	public String invspec ;// 规格
    	public String invpinpai;//品牌
    	public String unit ; //单位
    	public String invmodel;//型号
    	public String sfvbatchcode;//sf的批次号
    	public Decimal sfnum ;//备货数量
    	public String sfinvaliddate ;//SF 失效期

    	public String  frozenum ;//冻结数
    	public String  frozebatchecode;//冻结批次
    	public String  frozeinvaliddate;//冻结失效期

		public String  frozebatchecode1;//冻结批次
    	public String  frozeinvaliddate1;//冻结失效期

    	public String outnum;//出库数量
    	public String outbatchecode ;//出库批次

    	public String resnum;//剩余数量
    //	public String resbatchcode;//剩余批次
    	//public String resinvaliddate;//剩余失效期
 
    	public String vdef3 ; //子表id
    	public String vdef4 ;//主表id 
    	//public String saleorder ;//销售订单号
    	
    	
    	public String year ;//年份
    	public String accid ;

    	public NCDataBean( Map<String,Object> o, SameBatchNumber__c sbn ){
    		if(sbn != null){
    			name = sbn.name ;
    			h_name = sbn.CargoDetail__r.Name ;
    			accid = sbn.CargoDetail__r.Customer__c ;
    			custname = sbn.CargoDetail__r.Customer__r.Name;
    			invname  = sbn.Inventory__r.ProductName__c == null ? sbn.Inventory__r.Name : sbn.Inventory__r.ProductName__c;
    			invcode = sbn.Inventory__r.NCCode__c;
    			invmnecode = sbn.Inventory__r.SerialNo__c;
    			invspec = sbn.Inventory__r.Spec__c;
    			invpinpai = sbn.Inventory__r.Brand__c;
    			unit = sbn.Inventory__r.Unit__c;
    			invmodel = sbn.Inventory__r.Model__c;

    			sfvbatchcode = sbn.BatchNumber__c;
    			sfnum = sumAmount(sbn);
    			year = sbn.SendYear__c; 
    			sfinvaliddate  = sbn.ExpirationDate__c == null ? '': Utils.date2string(sbn.ExpirationDate__c, 'yyyy-MM-dd');
                vdef3 = sbn.Id;
    		}
    		
    		if(o != null){

    			frozenum = String.valueOf(o.get('totalfreezenum'));
    			frozebatchecode = String.valueOf(o.get('fz_vlot'));
    			frozeinvaliddate = String.valueOf(o.get('fz_dvdate'));

    			frozebatchecode1 = String.valueOf(o.get('fz_vlot'));
    			frozeinvaliddate1 = String.valueOf(o.get('fz_dvdate'));
    			outnum = String.valueOf(o.get('ck_num'));
    			outbatchecode = String.valueOf(o.get('ck_vlot'));

    			resnum = String.valueOf(o.get('lastfreezenum'));
    			
    		}

    		

    		
    	}
    	private Decimal  sumAmount(SameBatchNumber__c sn  ){
    		Decimal	a1 = sn.SendMount1__c == null ? 0 : sn.SendMount1__c ;
    		Decimal	a2 = sn.SendMount2__c == null ? 0 : sn.SendMount2__c ;
    		Decimal a3 = sn.SendMount3__c == null ? 0 : sn.SendMount3__c ;

	    	Decimal	a4 = sn.SendMount4__c == null ? 0 : sn.SendMount4__c ;
	    	Decimal	a5 = sn.SendMount5__c == null ? 0 : sn.SendMount5__c ;
	    	Decimal	a6 = sn.SendMount6__c == null ? 0 : sn.SendMount6__c ;

	    	Decimal	a7 = sn.SendMount7__c == null ? 0 : sn.SendMount7__c ;
	    	Decimal	a8 = sn.SendMount8__c == null ? 0 : sn.SendMount8__c ;
	    	Decimal	a9 = sn.SendMount9__c == null ? 0 : sn.SendMount9__c ;

	    	Decimal	a11 = sn.SendMount11__c == null ? 0 : sn.SendMount11__c ;
	    	Decimal	a12 = sn.SendMount12__c == null ? 0 : sn.SendMount12__c ;
	    	Decimal	a10 = sn.SendMount10__c == null ? 0 : sn.SendMount10__c ;

    		return  a1 + a2 + a3 + a4 + a5 +a6 +a7 + a8 + a9 + a10 + a11 + a12;
    	}
    
    }


}